<?php
/**
 * 用户服务层
 * 2019.3.12
 * xiaosu
 */
namespace app\api\service;

use think\Db;

class UserService
{
	/**
	 * 获取用户信息
	 * $str  查询的字段
	 */
	public function getUser($where,$str='*')
	{
		$info = Db::name('shop_user')->field($str)->where($where)->find();
		return $info;
	}
	/**
	 * 更新用户表
	 */
	public function updateUser($where,$data)
	{
		$res = Db::name('shop_user')->where($where)->update($data);
		return $res;
	}
	/**
	 * 删除银行卡
	 */
	public function deleteCard($where)
	{
		$res = Db::name('credit')->where($where)->update(['is_del' => 2]);
		return $res;
	}
	/**
	 * 验证银行卡
	 * $acct_name     姓名
	 * $acct_pan      银行卡
	 * $cert_id       身份证
	 * $phone_num     手机号码
	 */
	public function checkCard($acct_name,$acct_pan,$cert_id='',$phone_num=''){
        $host = "http://lundroid.market.alicloudapi.com";
        $path = "/lianzhuo/verifi";
        $method = "GET";
        $appcode = "eaf8824a23384736b8cde69e89073829";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "acct_name=$acct_name&acct_pan=$acct_pan&cert_id=$cert_id&phone_num=$phone_num";
        $bodys = "";
        $url = $host . $path . "?" . $querys;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        return json_decode(curl_exec($curl));
    }
    /**
     * 添加银行卡
     */
    public function addCard($data)
    {
    	Db::name('credit')->insert($data);
    }
    /**
     * 订单数
     */
    public function orderCount($where)
    {
    	$count = Db::name('order')->where($where)->count();
    	
    	return $count;
    }
    /**
     * 充值
     */
    public function recharge($money=0,$type,$user_id)
    {
    	$order_sn = cmf_get_order_sn();

    	$res = Db::name('recharge')->insert(['order_sn' => $order_sn, 'money' => $money, 'create_time' => time(), 'type' => $type,'user_id' => $user_id]);
    	
    	return ['status' => $res, 'order_sn' => $order_sn];
 
    }
    /**
     * 微信支付
     */
    public function WxPay($order_sn,$money)
    {
    	return  true;
    }
    /**
     * 获取用户是否申请中
     */
    public function applyPartner($where)
    {
    	$info = Db::name('partner')->where($where)->find();
    	return $info;
    }
    /**
     * 添加合伙人
     */
    public function addPartner($data)
    {
    	$res = Db::name('partner')->insert($data); 
    	return $res;
    }
    /**
     * 获取地址--判断地址是否存在
     */
    public function getAddress($where)
    {
    	$res = Db::name('region')->where($where)->find();
    	return $res;
    }
    /**
     * 获取申请合伙人的地址
     */
    public function partnerAddress($level)
    {
    	$address_list = [];
    	switch ($level) {
    		case '2':
    			$list = Db::name('region')->alias('a')->field('a.*,a.id as addr_id,b.parent_id as grandpa_id')->join('region b', 'a.parent_id=b.id', 'left')->select();

				foreach ($list as $li) {
		       
					switch ($li['level']) {
						case '1':
							$address_list[$li['addr_id']] = $li;
							break;
						case '2':
							$address_list[$li['parent_id']]['child'][$li['addr_id']] = $li;
							break;
						case '3':
							$address_list[$li['grandpa_id']]['child'][$li['parent_id']]['child'][] = $li;
						default:
							break;
					}
				}
				sort($address_list,1);
		        foreach ($address_list as $k=>$item) {
		            $item['grandpa_id'] = $item['grandpa_id'] ? $item['grandpa_id'] : '';
		            if(isset($item['child'])){
		                $child = array_values($item['child']);
		                sort($child,1);
		                $item['child'] = $child;
		            }else{
		                $item['child'] = array();
		            }

		            $address_list[$k] = $item;
				}

    			break;
    		case '3':
    			$list = Db::name('region')->alias('a')->field('a.*,a.id as addr_id')->where('level','in','1,2')->select();
    			
    			foreach ($list as $li) {
    				if ($li['level'] == 1) {
    					$address_list[$li['id']] = $li;
    				} else {
    					$address_list[$li['parent_id']]['child'][] = $li;
    				}
    			}
    			sort($address_list);
    			break;
    		case '4':
    			$address_list = Db::name('region')->alias('a')->field('a.*,a.id as addr_id')->where('level',1)->select();
    		default:
    			
    			break;
    	}
    	return $address_list;
    }
    /**
     * 获取下一级（含下下级）收入
     */
    public function agentList($user_id,$page,$size)
    {   
        //获取下级的用户
        $first_agent = Db::name('shop_user')->alias('a')
                     ->field('a.user_id,a.nick_name,a.user_name,sum(c.money) as count_money')
                     ->join('order b', 'a.user_id=b.user_id', 'left')
                     ->join('balance_record c', 'c.data_id=b.order_id', 'left')
                     ->where('a.first_leader',$user_id)
                     ->where('c.scene',5)
                     ->where('c.user_id',$user_id)
                     ->group('a.user_id')
                     ->limit(($page-1)*$size, $size)
                     ->select()->toArray();
        $count = Db::name('shop_user')->alias('a')
                     ->join('order b', 'a.user_id=b.user_id', 'left')
                     ->join('balance_record c', 'c.data_id=b.order_id', 'left')
                     ->where('a.first_leader',$user_id)
                     ->where('c.scene',5)
                     ->where('c.user_id',$user_id)
                     ->group('a.user_id')
                     ->count();
	    $f_arr = [];//遍历数组
        if (!empty($first_agent)) {
        	$f_ids = [];//下一级的id
        	
        	foreach ($first_agent as $fa) {
        		$f_ids[] = $fa['user_id'];
        		$fa['count_money'] = (float)$fa['count_money'];
        		$f_arr[$fa['user_id']] = $fa;
        	}
        	//获取下下级用户的统计
        	$second_agent = Db::name('shop_user')->alias('a')
                     ->field('a.user_id,a.nick_name,a.user_name,a.first_leader,sum(c.money) as count_money')
                     ->join('order b', 'a.user_id=b.user_id')
                     ->join('balance_record c', 'c.data_id=b.order_id')
                     ->where('a.first_leader','in',$f_ids)
                     ->where('c.scene',5)
                     ->where('c.user_id',$user_id)
                     ->group('a.user_id')
                     ->select()->toArray();
            
            if (!empty($second_agent)) {
            	foreach ($second_agent as $sa) {
            		
            		$f_arr[$sa['first_leader']]['count_money'] += (float)$sa['count_money'];
            	}
            }
            sort($f_arr);
        }
    	
      	return ['list' => $f_arr,'list_count' => $count];
    }
    /**
     * 总计的累计
     */
    public function countPaneter($user_id)
    {
    	$all_count = Db::name('balance_record')->where('user_id', $user_id)->where('scene',5)->sum('money');

    	return $all_count;
    }
    /**
     * 申请列表
     */
    public function applyList($user_id)
    {
    	$list = Db::name('partner')->where('user_id', $user_id)->select();
    	$level = config('member_level');
    	$status = ['申请中','通过','拒绝','撤销'];
    	$arr = [];
    	foreach ($list as $li) {
    		$li['status'] = $status[$li['status']];
    		$li['level_name'] = $level[$li['apply_level']];
    		$li['create_time'] = date('Y-m-d', $li['create_time']);
    		$arr[] = $li;
    	}
    	return $arr;
    }
    /**
     * 获取下一级的数量
     */
    public function lowLevelNum($user_id,$level)
    {
        $count = Db::name('shop_user')->where('first_leader',$user_id)->where('level',$level)->count();
        return $count;
    }
    /**
     * 撤销
     */
    public function revokePartner($pn_id,$user_id)
    {   
        $res = Db::name('partner')->where('pn_id', $pn_id)->where('user_id', $user_id)->find();
        if (empty($res)) {
            return ['status' => false, 'msg' => '撤销失败'];
        }
        if ($res['status'] != 1) {
            return ['status' => false, 'msg' => '非申请中无法撤销'];
        }

        $upd = Db::name('partner')->where('pn_id', $pn_id)->where('user_id', $user_id)->update(['status' => 4]);
        return ['status' => $upd, 'msg' => '撤销失败'];
    }
    /**
     * 申请合伙人列表
     */
    public function partnerApplyRecord($user_id,$page,$size)
    {
        $list = Db::name('partner')->alias('a')->field('a.*,b.name as address_name')->join('region b', 'a.address_id=b.id')->where('a.user_id', $user_id)->limit(($page-1)*$size, $size)->order('a.pn_id DESC')->select();

        $arr = [];
        $status = ['1' => '申请中','2' => '通过', '3' => '拒绝', '4' => '撤销'];
        $level = config('member_level');
        foreach ($list as $li) {
            $li['status_name'] = $status[$li['status']];
            $li['create_time'] = date('Y-m-d H:i:s', $li['create_time']);
            $li['apply_level'] = $level[$li['apply_level']];
            $arr[] = $li;
        }
        return $arr;
    }
    /**
     * 获取代理地址名
     */
    public function partnerAddressName($user_id,$level)
    {
        $address_id = Db::name('region')->where('user_id',$user_id)->value('id');
        if (empty($address_id)) {
            return [];
        }
        switch ($level) {
            case '3':
                $info = Db::name('region')->alias('a')->field('a.name as area,b.name as city,c.name as province')->join('region b','a.parent_id=b.id')->join('region c','b.parent_id=c.id')->where('a.id',$address_id)->find();
                return $info['province'].'-'.$info['city'].'-'.$info['area'];
                break;
            case '4':
                $info = Db::name('region')->alias('a')->field('a.name as city,b.name as province')->join('region b','a.parent_id=b.id')->where('a.id',$address_id)->find();
                return $info['province'].'-'.$info['city'];
                break;
            case '5':
                $info = Db::name('region')->where('id',$address_id)->value('name');
                return $info;
                break;
            default:
                return [];
                break;
        }
    }
    /**
     * 获取申请条数
     */
    public function applyRecordCount($user_id)
    {
        $count = Db::name('partner')->where('user_id', $user_id)->count();
        return $count;
    }
}